package com.centling.smartSealForPhone.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.utils.GlideApp;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.view.RoundImgView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

public class EditSelfInfoActivity extends TitleBarActivity implements View.OnClickListener {

    File tempFile = new File("/sdcard/temp.jpg");
    Uri imageUri = Uri.fromFile(tempFile);
    private RoundImgView avatar;
    private EditText username;
    private EditText realname;
    private EditText phone;
    private Button submit;
    private RelativeLayout setImgLayout;
    private AlertDialog dialog;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_self_info);
        setTitleBarText("编辑信息");
        initView();
        setData();
    }

    public void initView() {
        avatar = (RoundImgView) findViewById(R.id.edit_info_avatar);
        username = (EditText) findViewById(R.id.edit_info_username);
        realname = (EditText) findViewById(R.id.edit_info_realname);
        phone = (EditText) findViewById(R.id.edit_info_phone);
        submit = (Button) findViewById(R.id.edit_info_submit);
        setImgLayout = (RelativeLayout) findViewById(R.id.edit_info_pic);

        setImgLayout.setOnClickListener(this);
        submit.setOnClickListener(this);
    }

    public void setData() {
        Bundle bundle = getIntent().getExtras();
        GlideApp.with(EditSelfInfoActivity.this).load(bundle.getString("avatar")).placeholder(R.drawable.iv_avatar_default)
                .into(avatar);
        username.setText(bundle.getString("username"));
        realname.setText(bundle.getString("realname"));
        phone.setText(bundle.getString("phone"));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        try {
            if (resultCode != RESULT_CANCELED) {
                switch (requestCode) {
                    case 0:
                        startPhotoZoom(intent.getData());
                        break;
                    case Activity.DEFAULT_KEYS_DIALER:
                        startPhotoZoom(imageUri);
                        break;
                    case 2:
                        Bundle extras = intent.getExtras();
                        if (extras != null) {
                            bitmap = null;
                            try {
                                bitmap = BitmapFactory.decodeStream(
                                        getContentResolver().openInputStream(imageUri));
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            avatar.setImageBitmap(bitmap);
                        }
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 裁剪图片方法实现
     */
    public void startPhotoZoom(Uri uri) {
        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("return-data", false);
        startActivityForResult(intent, 2);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.edit_info_pic:
                if (dialog == null) {
                    dialog = new AlertDialog.Builder(EditSelfInfoActivity.this).setItems(new String[]{"相机", "相册"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
                                i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                startActivityForResult(i, Activity.DEFAULT_KEYS_DIALER);
                            } else {
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_PICK);
                                intent.setType("image/*");
                                startActivityForResult(intent, 0);
                            }
                        }
                    }).create();
                }
                if (!dialog.isShowing()) {
                    dialog.show();
                }
                break;

            case R.id.edit_info_submit:
                String userName = username.getText().toString();
                final String realName = realname.getText().toString();
                String phoneNum = phone.getText().toString();

                if (TextUtils.isEmpty(userName)) {
                    ShowToast.shortTime("用户名不能为空");
                } else if (TextUtils.isEmpty(realName)) {
                    ShowToast.shortTime("真实姓名不能为空");
                } else if (TextUtils.isEmpty(phoneNum)) {
                    ShowToast.shortTime("手机号不能为空");
                } else if (bitmap == null) {
                    ShowToast.shortTime("请选择头像");
                } else {
                    String id = SPUtil.getString(SPConstants.USER_ID);

                    ByteArrayOutputStream myStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, myStream);
                    byte[] copyByte = myStream.toByteArray();
                    int myLength = copyByte.length;
                    String bitmapData = Base64.encodeToString(copyByte, 0, myLength, Base64.DEFAULT);

                    Map<String, String> param = new HashMap<>();
                    param.put("id", id);
                    param.put("userName", userName);
                    param.put("phone", phoneNum);
                    param.put("realName", realName);
                    param.put("avatar", bitmapData);
                    postJsonEnqueue(UrlConstants.EDIT_USERINFO, param, new OkHttpUtil.NetCallBack() {
                        @Override
                        public void onSucceed(String json) {
                            ShowToast.shortTime("修改个人信息成功");
                            finish();
                        }

                        @Override
                        public void onFailed(String reason) {
                            ShowToast.shortTime(reason);
                        }
                    });
                }
            default:
                break;
        }
    }
}
